﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using CUWo.App.Views;
using CUWo.Common;
using CUWo.Common.Entities;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.StorageHelper;
using CUWo.Common.WebHelper;
using CUWo.Common.WoInterfaceCommunication;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using WheelFlow;

namespace CUWo.App.CustomControl.Active
{
    public class FlowItem
    {
        public string Id { get; set; }

        public string Title { get; set; }

        public string Abstract { get; set; }

        public string Content { get; set; }

        public string NavigateUrl { get; set; }
        public double PictureHeight { get; set; }

        public double PictureWidth { get; set; }
        public ImageSource Picture { get; set; }
        public ImageBrush BackupgroupPicture { get; set; }
    }

    public partial class CCActiveInfo : UserControl
    {
        private ObservableCollection<FlowItem> pictureList = new ObservableCollection<FlowItem>();

        /// <summary>
        /// 是否执行Tab事件
        /// </summary>
        private bool isExecuteTabHandler = true;

        public WebViewPage navigatePopup { get; set; }

        public CCActiveInfo()
        {
            InitializeComponent();

            //绑定本地数据
            //this.BindActivePicture();
            //服务器数据绑定

        }

        public void LoadData()
        {
            string mobileNumber = string.Empty;
            var romInfoString = IsolatedStorageHelper.Instance.ReadText(Keys.ROM_FILENAME);
            if (!string.IsNullOrWhiteSpace(romInfoString))
            {
                RomInfo romInfo = JSONHelper.Deserialize<RomInfo>(romInfoString);
                if (romInfo != null)
                {
                    mobileNumber = romInfo.Mobile;
                }
            }
            if (string.IsNullOrWhiteSpace(mobileNumber))
            {
                MessageToastManager.Show("未登录，请登录！", MessageToastLevel.Warn);
                return;
            }
            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.ActiveInfo().GetUrl(mobileNumber);
            LogHelper.LogInfo(requestUrl);
            //

            PopupProgressBar.OpenProgressBar();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultMessageActiveInfo activeInfo = JSONHelper.Deserialize<JsonResultMessageActiveInfo>(decryptStringResult);
                            if (activeInfo != null)
                            {
                                if (activeInfo.Msg != null)
                                {
                                    if (activeInfo.Msg.MessageErrors != null && activeInfo.Msg.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(activeInfo.Msg.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (activeInfo.Msg.MessageWarns != null && activeInfo.Msg.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(activeInfo.Msg.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (activeInfo.Msg.MessagePrompts != null && activeInfo.Msg.MessagePrompts.Count > 0)
                                        {
                                            BindData(activeInfo.ActInf);
                                        }
                                    }
                                }
                            }
                          
                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        void BindData(IList<ActInf> activeInfos)
        {
            if (activeInfos != null && activeInfos.Count > 0)
            {
                int i = 1;
                foreach (ActInf item in activeInfos)
                {
                    FlowItem fi = new FlowItem();
                    if (item.ActPicInf != null)
                    {
                        var imageSource = new StorageCachedImage(new Uri(item.ActPicInf.Path, UriKind.Absolute));
                        fi.Picture = imageSource;
                        fi.BackupgroupPicture = new ImageBrush() { ImageSource = imageSource };
                        fi.PictureHeight = item.ActPicInf.Height;
                        fi.PictureWidth = item.ActPicInf.Width;
                    }
                    fi.Id = i.ToString();
                    fi.Title = item.ActNm;
                    fi.Abstract = DateTimeToAbstract(item.BgnDtTm, item.EndDtTm);
                    fi.Content = item.ActCon;
                    fi.NavigateUrl = item.Lnk;
                    this.pictureList.Add(fi);
                    if (i == 1)
                    {
                        this.txtbTitle.Text = fi.Title;
                        this.txtbAbstract.Text = fi.Abstract;
                        this.txtbContent.Text = fi.Content;
                    }
                    i++;
                }

                this.fic3d.ItemsSource = pictureList;
                this.fic3d.SelectionChanged += fic3d_SelectionChanged;
            }
            else
            {
                MessageToastManager.Show("无活动信息！", MessageToastLevel.Info);
            }
        }

        string DateTimeToAbstract(string beginDateTime, string endDateTime)
        {
            var bdt = DateTime.ParseExact(beginDateTime, "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
            var edt = DateTime.ParseExact(endDateTime, "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
            return string.Concat(bdt.ToString("yyyy年MM月dd日"), "~", edt.ToString("yyyy年MM月dd日"));
        }

        void fic3d_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            isExecuteTabHandler = false;
            LogHelper.LogInfo(string.Empty, this.GetType(), MethodBase.GetCurrentMethod());
            FlowItem item = (this.fic3d.SelectedItem as FlowItem);
            if (item != null)
            {
                this.txtbTitle.Text = item.Title;
                this.txtbAbstract.Text = item.Abstract;
                this.txtbContent.Text = item.Content;
            }
        }

        private void InFlowContentControl_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            LogHelper.LogInfo(string.Empty, this.GetType(), MethodBase.GetCurrentMethod());
            if (this.isExecuteTabHandler)
            {
                FlowItem item = (this.fic3d.SelectedItem as FlowItem);
                if (item != null)
                {
                    //MessageBox.Show("跳转至详细页......");
                    this.navigatePopup = new WebViewPage(item.NavigateUrl);
                }
            }
            this.isExecuteTabHandler = true;
        }

        private void InFlowContentControl_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //LogHelper.LogInfo(string.Empty, this.GetType(), MethodBase.GetCurrentMethod());

            //FlowItem item = (this.fic3d.SelectedItem as FlowItem);
            //if (item != null)
            //{
            //    this.txtbTitle.Text = item.Title;
            //    this.txtbAbstract.Text = item.Abstract;
            //    this.txtbContent.Text = item.Content;
            //}
        }

        private void BindActivePicture()
        {
            FlowItem fi1 = new FlowItem() { PictureWidth = 398, PictureHeight = 277 };
            BitmapImage bi1 = new BitmapImage() { UriSource = new Uri("/Images/tmp/active01.png", UriKind.Relative) };
            fi1.Picture = bi1;
            fi1.Title = "天天跑酷";
            fi1.Abstract = "开始结束日期";
            fi1.Content = "《天天跑酷》是一款无需联网即可运行的横版跑酷游戏。秉承《天天酷跑》、《旋风跑跑(Wind Runner)》等游戏的优点，并在难度和操作体验上加以改善。画面清新，风格酷炫可爱，4款多变场景让你体验从沙漠穿越到北极的爽快。";
            fi1.Id = "1";
            fi1.NavigateUrl = "http://www.qq.com";
            fi1.BackupgroupPicture = new ImageBrush() { ImageSource = bi1 };
            //
            FlowItem fi2 = new FlowItem() { PictureWidth = 398, PictureHeight = 277 };
            BitmapImage bi2 = new BitmapImage() { UriSource = new Uri("/Images/tmp/active02.png", UriKind.Relative) };
            fi2.Picture = bi1;
            fi2.Title = "应用家";
            fi2.Abstract = "内容介绍";
            fi2.Content = "《应用家》定位于Windows Phone上最有价值的、最接地气的应用商店。具有智能APP推荐和语音搜索等功能，不仅能让用户快速下载到自己想要的应用，而且通过独家的视频介绍帮助用户能够更加深入地了解推荐APP的内容及玩法，有效提高用户体验。";
            fi2.Id = "2";
            fi2.NavigateUrl = "http://www.huanqiu.com";
            fi2.BackupgroupPicture = new ImageBrush() { ImageSource = bi2 };
            //
            FlowItem fi3 = new FlowItem() { PictureWidth = 398, PictureHeight = 277 };
            BitmapImage bi3 = new BitmapImage() { UriSource = new Uri("/Images/tmp/active03.png", UriKind.Relative) };
            fi3.Picture = bi1;
            fi3.Title = "标题";
            fi3.Abstract = "开始结束日期";
            fi3.Content = "内容介绍";
            fi3.Id = "3";
            fi3.NavigateUrl = "http://www.xboxad.com";
            fi3.BackupgroupPicture = new ImageBrush() { ImageSource = bi3 };
            //
            pictureList.Add(fi1);
            pictureList.Add(fi2);
            pictureList.Add(fi3);
            //
            this.txtbTitle.Text = fi1.Title;
            this.txtbAbstract.Text = fi1.Abstract;
            this.txtbContent.Text = fi1.Content;

            this.fic3d.ItemsSource = pictureList;
            this.fic3d.SelectedItem = fi1;//默认选择项，必须设置此项，否则后面的Tap事件就有问题了
            this.fic3d.SelectionChanged += fic3d_SelectionChanged;
        }


        
    }
}
